const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
const Role = require('../models/Role');

// 获取所有角色
router.get('/', auth, async (req, res) => {
  try {
    const roles = await Role.find().populate('permissions');
    res.json(roles);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 创建角色
router.post('/', auth, async (req, res) => {
  try {
    const { name, description, permissions } = req.body;
    const role = new Role({
      name,
      description,
      permissions
    });
    await role.save();
    res.status(201).json(role);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 更新角色
router.put('/:id', auth, async (req, res) => {
  try {
    const { name, description, permissions } = req.body;
    const role = await Role.findByIdAndUpdate(
      req.params.id,
      { name, description, permissions },
      { new: true }
    ).populate('permissions');
    
    if (!role) {
      return res.status(404).json({ message: '角色不存在' });
    }
    
    res.json(role);
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

// 删除角色
router.delete('/:id', auth, async (req, res) => {
  try {
    const role = await Role.findByIdAndDelete(req.params.id);
    if (!role) {
      return res.status(404).json({ message: '角色不存在' });
    }
    res.json({ message: '角色已删除' });
  } catch (error) {
    res.status(500).json({ message: '服务器错误' });
  }
});

module.exports = router; 